package web.controller;

import com.alibaba.fastjson.JSONObject;
import common.bean.SearchPageResult;
import common.tag.easyui.DataGrid;
import common.tag.easyui.TagUtils;
import module.model.ServiceModel;
import module.service.ServiceModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
@RequestMapping(value = "/admin/service")
public class ServiceController extends BaseController{
    public final static String prefix="admin/module/service/";

    @Autowired
    private ServiceModelService serviceModelService;
    protected String getPrefix() {
        return prefix;
    }

    @RequestMapping(value = "list",method = RequestMethod.POST)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    public void list(DataGrid dataGrid){
        SearchPageResult<ServiceModel> serviceModelSearchPageResult = serviceModelService.getServiceModelListPage(dataGrid.getPage());
        dataGrid.setResults(serviceModelSearchPageResult.getResult());
        dataGrid.setTotal(serviceModelSearchPageResult.getTotal());
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Cache-Control", "no-store");
        JSONObject object = TagUtils.getJson(dataGrid);
        try {
            PrintWriter pw=response.getWriter();
            pw.write(object.toString());
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "form",method = RequestMethod.GET)
    public String form(Long serviceId,ModelMap map){
        if(serviceId!=null){
            map.put("serviceModel",serviceModelService.getServiceModelByServiceId(serviceId));
        }

        return prefix+"form";
    }

    @RequestMapping(value = "save",method = RequestMethod.POST)
    @ResponseBody
    public ModelMap save(ServiceModel serviceModel){
        ModelMap map = new ModelMap();
        setFailure(map);
        try{
            if(serviceModel.getServiceId()==null){
                serviceModel.setCreateUserId(getCurAdminId());
                serviceModelService.saveServiceModel(serviceModel);
            }else{
                serviceModel.setLastUpdateUserId(getCurAdminId());
                serviceModelService.updateServiceModel(serviceModel);
            }
            setSuccess(map);
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }
}
